// Every two seconds the Client uploads a new timestamp with its coorresponding ID#
package Threads;

import ClientComm.ConnectionObject;

/**
 * This thread is responsible for continuously updating a timestamp
 * in the database in order to not time out.  This is done so that
 * users are given the opportunity to access the physical robots in a queue
 * such that only 1 user may operate the robots at a time.  Utilizes a
 * first in first out (FIFO) prioritization.
 *
 * @author      Dakota Brown, Travis Shuff
 */
public class QueueClient implements Runnable {

    public static int position = 0;
    public static String id = "", queuePos = "";
    public static boolean run = false;
    private ConnectionObject conObj;    

    /**
     * Default Constructor
     */
    public QueueClient(ConnectionObject conObj, String queuePos) {
        this.conObj = conObj;
        this.queuePos = queuePos;
    }

    /**
     * Stops the threads execution
     */
    public void stop() {
        run = false;
    }
   
    /**
     * Creates a unique ID and inserts that id into the database along with
     * a time stamp.  Then, every 2 seconds it updates that timestamp with the
     * current time.  If other users have have timed out or have exited the
     * program the position in the queue is recalculated.
     */
    public void run() {
        id = conObj.buildID();
        run = true;
        boolean started = false;
        long start = 0, stop = 0;
        while (run) {
            try {
                position = conObj.updateID(id, position);
                queuePos = "Position in queue: " + position;
                if (position == 1) {
                    //starts a timer
                    if (!started) {
                        start = System.currentTimeMillis();
                        started = true;
                    }
                    stop = System.currentTimeMillis();
                    //15 minute time limit on position 1
                    if ((stop - start) > 900000) {
                        //puts user back into queue
                        id = conObj.buildID();
                        started = false;
                    }
                }
                Thread.sleep(2000);
            } catch (InterruptedException ex) {
                System.out.println("Queue failed");
            }
        }
        
        conObj.updateConnectivity(id);
    }
}
